package com.rrd.hive.udf;

import com.rrd.hive.util.PIDValidator;
import com.weicai.caesar.CaesarUtil;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


@Description(
        name = "pid_prex_sub",
        value = "_FUNC_(pid, len) - 获取身份证前len位，len<=4",
        extended = "Example:\n> SELECT _FUNC_('110106201012310313');\n  10\n> SELECT _FUNC_('110106201012310313',2);\n  11"
)
public class PidPrexSub extends UDF {

    public Text evaluate(String pid) {
        return evaluate(pid, 2);
    }

    public Text evaluate(String pid, int len) {
        if (pid == null || pid.equals("")) {
            return null;
        }
        Text res = new Text();
        if (CaesarUtil.isEncrypted(pid)) {
            pid = CaesarUtil.decode(pid);
        }
        if (pid.length() != 18 || !PIDValidator.isValidIDCard(pid)) {
            return null;
        }
        res.set(pid.substring(0,len));
        return res;
    }

    public static void main(String[] args) {
        PidPrexSub dfu = new PidPrexSub();
        System.out.println(dfu.evaluate(CaesarUtil.encode("110106198705170313"),4));
    }
}
